﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using blackhouse.BlackApart.Business;
using blackhouse.BlackApart.Business.ApartmentServices;
using blackhouse.BlackApart.Business.Payments;
using blackhouse.BlackApart.Business.Prices;
using blackhouse.BlackApart.Business.Reservations;
using blackhouse.BlackApart.Web;
using blackhouse.BlackApart.Web.Modules;
using blackhouse.BlackApart.Web.Navigation;
using blackhouse.Currencies;
using blackhouse.JavaScript.JQuery;
using blackhouse.mojoPortalExtend;
using blackhouse.mojoPortalExtend.Breadcrumbs;
//using blackhouse.Payments;
using mojoPortal.Web;
using System.Text;

namespace blackhouse.StareKino.Web {
    public partial class OnlineReservationPage : NonCmsBasePage {

        #region Fields

        private readonly Factory factory = Factory.Instance();
        private Variant variant;
        private double breakfastPrice;
        private double breakfastCost;

        protected int ActivePage;
        private bool error;

        private IWebReservation reservation;
        private ReservationAdditionalServicesOrder servicesOrder;
        private IEnumerable<ReservationAdditionalService> reservationOrderingServices;
        private ReservationAdditionalService reservationExtraBedService;

        private IPaymentType[] paymentTypes;

        private BreadcrumbsAccess breadcrumb;

        //private PayUConfig payConfig;
        //private PaymentTransaction transaction;

        private ApartmentWebReservation[] statusReservationItems;

        private ReservationPage reservationPage;
        private ReservationPrice reservationPriceCalculator;

        private Dictionary<string, double> informationServices;

        #endregion

        #region Properties

        private ReservationPage ReservationPage {
            get {
                return this.reservationPage ??
                       (this.reservationPage = NavigationProvider.Instance().GetReservationPageFromRequest());
            }
        }

        protected ReservationPrice ReservationPriceCalculator {
            get {
                return this.reservationPriceCalculator ??
                       (this.reservationPriceCalculator = new ReservationPrice(this.Reservation));
            }
        }

        private IWebReservation Reservation {
            get { return this.reservation ?? (this.reservation = this.ReservationPage.Reservation); }
        }

        private ReservationAdditionalServicesOrder ServicesOrder {
            get {
                return this.servicesOrder ??
                       (this.servicesOrder = this.GetReservationAdditionalServicesOrder(Reservation));
            }
        }

        private IEnumerable<ReservationAdditionalService> ReservationOrderingServices {
            get {
                return this.reservationOrderingServices ??
                       (this.reservationOrderingServices = this.ServicesOrder.GetOrderingReservationServices());
            }
        }

        private ReservationAdditionalService ReservationExtraBedService {
            get {
                return this.reservationExtraBedService ??
                       (this.reservationExtraBedService =
                           this.ServicesOrder.GetOrderingReservationServices()
                               .FirstOrDefault(rs => rs.Service.ServiceKey == "extrabed"));
            }
        }

        #endregion

        #region Event Handlers

        protected override void OnPreInit(EventArgs e) {
            this.AllowSkinOverride = true;
            HttpContext.Current.Items.Add("skin", "blackhouse");
            HttpContext.Current.Items.Add("short-top", true);
            HttpContext.Current.Items.Add("hide-footer", true);

            base.OnPreInit(e);
        }

        protected override void OnInit(EventArgs e) {
            base.OnInit(e);
            this.AddClassToBody("short-top");
        }

        protected override void OnLoad(EventArgs e) {
            base.OnLoad(e);

            if (!IsPostBack) {
                this.SetScenario();
                this.PopulateView();
            }
        }

        #endregion

        #region Methods

        private ReservationAdditionalServicesOrder GetReservationAdditionalServicesOrder(IWebReservation reservationForServices) {
            ReservationAdditionalServicesOrder order = null;
            Page page;
            if (HttpContext.Current != null) {
                page = HttpContext.Current.Handler as Page;
                if (page != null && page.Items.Contains("ReservationAdditionalServicesOrder-" + reservationForServices.ReservationId)) {
                    order = page.Items["ReservationAdditionalServicesOrder-" + reservationForServices.ReservationId] as ReservationAdditionalServicesOrder;
                }
            }
            if (order != null) return order;
            order = new ReservationAdditionalServicesOrder(reservationForServices);
            if (HttpContext.Current == null) return order;
            page = HttpContext.Current.Handler as Page;
            if (page != null)
                page.Items.Add("ReservationAdditionalServicesOrder-" + reservationForServices.ReservationId, order);
            return order;
        }

        private void SetPageSeo() {
            var pp = new PageProvider();
            mojoPortal.Business.PageSettings p = pp.FindCmsPageByFunctionality("reservationForServices");
            if (p != null) {
                pp.TrySetFromCms(p);
                this.breadcrumb = new BreadcrumbsAccess();
                breadcrumb.AddCrumb(p.PageName, NavigationProvider.Instance().GetUrl(ReservationPage.GetInformationPage(0)));
            }
        }

        private void SetScenario() {
            if (this.ReservationPage == null) {
                this.error = true;
                return;
            }

            if (ReservationPage.Type == ReservationSubpageType.PreInformation) {
                if (!this.SetScenarioForPreInformation()) {
                    this.error = true;
                    return;
                }
            }

            if (ReservationPage.Type == ReservationSubpageType.Information) {
                if (!this.SetScenarioForInformation()) {
                    this.error = true;
                    return;
                }
            }

            if (ReservationPage.Type == ReservationSubpageType.Contact) {
                if (!this.SetScenarioForContact()) {
                    this.error = true;
                    return;
                }
            }

            if (ReservationPage.Type == ReservationSubpageType.Payment) {
                if (!this.SetScenarioForPayments()) {
                    this.error = true;
                    return;
                }
            }
            if (this.ReservationPage.Type == ReservationSubpageType.EndReservation) {
                if (!this.SetScenarioForEnd()) {
                    this.error = true;
                    return;
                }
            }
            if (this.ReservationPage.Type == ReservationSubpageType.Confirm) {
                if (!this.SetScenarioForConfirm()) {
                    this.error = true;
                    return;
                }
            }
            if (this.ReservationPage.Type == ReservationSubpageType.Status) {
                if (!this.SetScenarioForStatus()) {
                    this.error = true;
                }
            }
        }

        private bool ReservationIsValid() {
            return this.ReservationPage != null && this.Reservation != null && this.ReservationPriceCalculator != null;
        }

        private bool SetScenarioForEnd() {
            return this.ReservationIsValid();
        }

        private bool SetScenarioForConfirm() {
            if (!this.ReservationIsValid()) return false;
            this.Reservation.ChangeStatus("confirm");
            return true;
        }

        public double GetReservationTotalCost() {
            return this.Reservation.FinalPrice;
        }

        public string GetUserIP() {
            var ipList = Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
            return !string.IsNullOrEmpty(ipList) ? ipList.Split(',')[0] : Request.ServerVariables["REMOTE_ADDR"];
        }

        private bool SetScenarioForPayments() {
            if (this.ReservationIsValid()) {
                this.paymentTypes = factory.GetPaymentType().GetWebPayments();
                if (paymentTypes.Length > 0) {
                    this.paymentTypes = this.paymentTypes.OrderByDescending(pt => pt.ExtraRabat).ToArray();
                    return true;
                }
            }
            return false;
        }

        private bool SetScenarioForContact() {
            return this.ReservationIsValid();
        }

        private bool SetScenarioForStatus() {
            if (this.ReservationIsValid()) {
                this.statusReservationItems = this.Reservation.ApartmentReservation;
                return true;
            }
            return false;
        }

        private bool SetScenarioForPreInformation() {
            if (!this.ReservationPage.State.IsSet || this.ReservationPage.ApartmentTypeId == 0)
                return false;

            var search = this.ReservationPage.State.GetSearchVariants();
            search.FilterToApartmentType(this.ReservationPage.ApartmentTypeId);
            this.variant = search.FirstOrDefault();
            if (this.variant == null)
                return false;

            var webRabat = this.factory.GetPriceRabat().GetRabat("web");
            if (webRabat != null)
                this.variant.Price.ApplyPriceRabat(webRabat);
            var breakfastService = this.factory.GetAdditionalService().FindService(this.variant.GetGroups().First().Id, "breakfasts");
            if (breakfastService != null)
                this.breakfastPrice = breakfastService.UnitPrice;
            this.breakfastCost =
                new DefaultAdditionalServicePrice(breakfastService, search.ArrivalDate, search.DepartureDate,
                    search.ForPeopleCount).Price;
            return true;
        }

        private bool SetScenarioForInformation() {
            if (!this.ReservationPage.State.IsSet || this.ReservationPage.ApartmentTypeId == 0)
                return false;

            FreeApartments search = this.ReservationPage.State.GetSearchVariants();
            search.FilterToApartmentType(this.ReservationPage.ApartmentTypeId);
            this.variant = search.FirstOrDefault();
            if (this.variant == null)
                return false;

            IPriceRabat webRabat = this.factory.GetPriceRabat().GetRabat("web");
            if (webRabat != null)
                this.variant.Price.ApplyPriceRabat(webRabat);
            if (this.variant.Price is PriceWithAdditionalServices) {
                var addPrice = this.variant.Price as PriceWithAdditionalServices;
                if (this.ReservationPage.OrderingBreakfasts)
                    addPrice.AddService(
                        Factory.Instance()
                            .GetAdditionalService()
                            .FindService(this.variant.GetGroups().First().Id, "breakfasts"));

                this.informationServices = new Dictionary<string, double>();
                foreach (IAdditionalService additionalService in addPrice.GetServices()) {
                    informationServices.Add(additionalService.ServiceName, addPrice.GetServicePrice(additionalService));
                }
            }
            return true;
        }

        private void PopulateView() {
            if (error) {
                this.PopulateErrorView();
                return;
            }
            this.SetPageSeo();
            if (ReservationPage.Type == ReservationSubpageType.PreInformation)
                this.PopulatePreInformationView();
            if (ReservationPage.Type == ReservationSubpageType.Information)
                this.PopulateInformationView();
            if (this.ReservationPage.Type == ReservationSubpageType.Contact)
                this.PopulateContactView();
            if (this.ReservationPage.Type == ReservationSubpageType.Payment)
                this.PopulatePaymentView();
            if (this.ReservationPage.Type == ReservationSubpageType.EndReservation)
                this.PopulateEndView();
            if (this.ReservationPage.Type == ReservationSubpageType.Confirm)
                this.PopulateConfirmView();
            if (this.ReservationPage.Type == ReservationSubpageType.Status)
                this.PopulateStatusView();

            //jql.IncludeFileBasedOnJQuery("blackhouse.Aparts.Web.Scripts.web-reservationForServices.js,blackhouse.Aparts.Web");
        }

        private void PopulateEndView() {
            // ReSharper disable once PossibleNullReferenceException
            this.SetSubtitle(0, GetGlobalResourceObject("Reservation", "reservationH5").ToString());
            this.ltlReservationClientEmail.Text = this.Reservation.Client.EMail;
            this.ltlReservationNumber.Text = this.Reservation.ReservationNumber;
            this.lnkReservationStatus.NavigateUrl = NavigationProvider.Instance().GetUrl(ReservationPage.GetStatusPage(this.Reservation));
            if (this.breadcrumb != null)
                // ReSharper disable once PossibleNullReferenceException
                this.breadcrumb.AddCrumb(GetGlobalResourceObject("Reservation", "completeBooking").ToString(), "");
            this.mvView.SetActiveView(vEnd);
        }

        private void PopulateConfirmView() {
            this.SetAlternativeTitle(GetGlobalResourceObject("Reservation", "confirmBookingText") + " " + this.Reservation.ReservationNumber);
            this.lnkDisplayReservation.Text = string.Format(this.lnkDisplayReservation.Text, this.Reservation.ReservationNumber);
            this.lnkDisplayReservation.NavigateUrl = NavigationProvider.Instance().GetUrl(ReservationPage.GetStatusPage(this.Reservation));
            if (this.Reservation.PaymentType.Key == "payu") {
                this.pnlOnlinePayment.Visible = true;
                this.lnkToPayment.NavigateUrl = NavigationProvider.Instance().GetUrl(ReservationPage.GetProcessPayPage(this.Reservation));
            }
            this.mvView.SetActiveView(vConfirm);
        }

        private void PopulatePaymentView() {
            // ReSharper disable once PossibleNullReferenceException
            this.SetSubtitle(3, GetGlobalResourceObject("Reservation", "selectPaymentType").ToString());
            this.rptPayments.DataSource = this.paymentTypes;
            this.rptPayments.DataBind();

            this.curReservationCostAbPayment.Value = this.ReservationPriceCalculator.TotalCost;
            this.curTotalReservationCost.Value = this.ReservationPriceCalculator.TotalCost;

            if (this.breadcrumb != null)
                // ReSharper disable once PossibleNullReferenceException
                this.breadcrumb.AddCrumb(GetGlobalResourceObject("Reservation", "reservationM3_1").ToString(), "");
            this.mvView.SetActiveView(this.vPayment);
            var jql = new JQueryLibraries();
            jql.IncludeFileBasedOnJQuery("blackhouse.StareKino.Web.Scripts.onlineReservation.Payment.js,blackhouse.StareKino.Web");
        }

        private void PopulateContactView() {
            // ReSharper disable once PossibleNullReferenceException
            this.SetSubtitle(2, GetGlobalResourceObject("Reservation", "reservationH6").ToString());
            if (this.breadcrumb != null)
                // ReSharper disable once PossibleNullReferenceException
                this.breadcrumb.AddCrumb(GetGlobalResourceObject("Reservation", "reservationM2_1").ToString(), "");
            var pp = new PageProvider();
            var p = pp.FindCmsPageByFunctionality("policy");
            if (p != null)
                this.lnkPrivatePolicy.NavigateUrl = p.Url;
            else
                this.lnkPrivatePolicy.Visible = false;
            this.lblNextDayArrival.Style.Add(HtmlTextWriterStyle.Display, "none");
            this.lblNextDayArrival.Text = this.Reservation.ArrivalDate.AddDays(1).ToString("D");
            this.lnkContactComplete.Text = GetGlobalResourceObject("Reservation", "gotoStep") + @":<br />" + GetGlobalResourceObject("Reservation", "reservationM3_1");

            this.mvView.SetActiveView(this.vReservationClient);
        }

        private void PopulatePreInformationView() {
            // ReSharper disable once CompareOfFloatsByEqualityOperator
            var informationPage = ReservationPage.GetInformationPage(this.ReservationPage.ApartmentTypeId);
            var navigation = NavigationProvider.Instance();
            // ReSharper disable once CompareOfFloatsByEqualityOperator
            if (this.breakfastCost == 0)
                Response.Redirect(navigation.GetUrl(informationPage));

            var globalResourceObject = GetGlobalResourceObject("Reservation", "reservationH7");
            if (globalResourceObject != null)
                this.SetSubtitle(1, globalResourceObject.ToString());
            this.ltlBreakfastOneValue.Value = this.breakfastPrice;
            this.ltlBreakfastsValue.Value = this.breakfastCost;
            this.lnkToInformationWithoutBreakfasts.NavigateUrl = navigation.GetUrl(informationPage);
            informationPage.OrderingBreakfasts = true;
            this.lnkToInformationWithBreakfasts.NavigateUrl = navigation.GetUrl(informationPage);
            this.mvView.SetActiveView(this.vReservationPreInfo);
        }


        private void PopulateInformationView() {
            // ReSharper disable once PossibleNullReferenceException
            this.SetSubtitle(1, GetGlobalResourceObject("Reservation", "reservationH7").ToString());
            if (variant.ApartmentCount > 1) {
                this.ltlApartmentsCount.Text = variant.ApartmentCount + @"x ";
                this.ltlApartmentsCount.Visible = true;
            }
            var group = this.variant.GetGroups().First();
            this.lblApartmentName.Text = group.ShortName;
            this.imgApartmentPhoto.ImageUrl = StareKinoHelper.GetApartmentPhotoUrl(group.MainPhoto, new System.Drawing.Size(480, 480));
            this.imgApartmentPhoto.AlternateText = group.Name;
            if (variant.Price is PriceWithAdditionalServices) {
                this.lblNumberPeoples.Text = (variant.Price.ReservationNumberOfPeoples - 1).ToString(CultureInfo.InvariantCulture);
                this.lblPeoples.Text = this.GetPersonText(variant.Price.ReservationNumberOfPeoples - 1) + @" (" + GetGlobalResourceObject("Apartments", "extraBed") + @")";
            } else {
                var numberOfPeoples = this.variant.Items.Sum(i => i.NumberOfPeoples);
                //int maxNumberOfPeoples = this.variant.GetGroups().Sum(g => g.NumberOfPeople);
                this.lblNumberPeoples.Text = numberOfPeoples.ToString(CultureInfo.InvariantCulture);
                this.lblPeoples.Text = this.GetPersonText(numberOfPeoples);
            }
            this.ltlPeriod.Text = this.variant.Items[0].ArrivalDate.FormatDateRange(this.variant.Items[0].DepartureDate);
            var lengthStay = (int)Math.Round((this.variant.Items[0].DepartureDate - this.variant.Items[0].ArrivalDate).TotalDays, 0);
            var lengthStayText = lengthStay + " ";
            var resxKey = "nights1";
            if (lengthStay > 1 && lengthStay <= 4)
                resxKey = "nights24";
            if (lengthStay > 4)
                resxKey = "nightsmore";
            lengthStayText += GetGlobalResourceObject("Reservation", resxKey);
            this.ltlLengthOfStay.Text = lengthStayText;
            if (this.informationServices != null && this.informationServices.Count > 0) {
                var pas = this.variant.Price as PriceWithAdditionalServices;
                if (pas != null)
                {
                    this.ltlComplexApartmentReservationValue.Value = pas.GetApartmentPriceWithoutRabat();
                    this.ltlComplexReservationValue.Value = pas.GetPriceWithoutRabat();
                }
                this.rptInformationServices.DataSource = this.informationServices;
                this.rptInformationServices.DataBind();
                this.phComplexReservationValue.Visible = true;
                this.ltlReservationValue.Visible = false;
                this.ltlTotalRabatWarning.Visible = true;
            } else
                this.ltlReservationValue.Value = this.variant.Price.GetPriceWithoutRabat();
            //this.lblMaxNumberPeoples.Text = maxNumberOfPeoples + " " + this.GetPersonText(maxNumberOfPeoples);
            //this.lblArrivalDate.Text = this.variant.Items[0].ArrivalDate.ToString("d MMMM yyyy");
            //this.lblDepartureDate.Text = this.variant.Items[0].DepartureDate.ToString("d MMMM yyyy");
            //this.lblPrice.Value = this.variant.Price.GetPrice();
            //this.lblPreviousPrice.Value = this.variant.Price.GetPriceWithoutRabat();
// ReSharper disable once CompareOfFloatsByEqualityOperator
            if (this.variant.Price.GetRabatValue() != 0) {
                this.reservationRabat.Visible = true;
                this.ltlTotalRabat.Text = String.Format("{0:F0}%", this.variant.Price.GetRabatValue());
                IPriceRabat[] rabats = this.variant.Price.GetAssociacedRabats();
                if (rabats.Length > 0) {
                    this.rptRabats.Visible = true;
                    this.rptRabats.DataSource = rabats;
                    this.rptRabats.DataBind();
                }
                //this.ltlDiscounts.Text = String.Join("<br />", rNames);
                //this.ltlDiscountsValue.Text = String.Join("<br />", rValues);
            } else {
                this.reservationRabat.Visible = false;
            }
            this.ltlReservationFinalValue.Value = this.variant.Price.GetPrice();
            if (this.breadcrumb != null)
                this.breadcrumb.AddCrumb(GetGlobalResourceObject("Reservation", "informationToBook").ToFirstUpperString(), "");
            this.lnkGotoContact.Text = GetGlobalResourceObject("Reservation", "gotoStep") + @":<br />" + GetGlobalResourceObject("Reservation", "reservationM2_1");
            this.mvView.SetActiveView(this.vReservationInfo);
        }

        private void PopulateStatusView() {
            this.SetAlternativeTitle(GetGlobalResourceObject("Reservation", "bookingStatus") + " " + this.Reservation.ReservationNumber);
// ReSharper disable once PossibleNullReferenceException
            this.SetSubtitle(0, GetGlobalResourceObject("Reservation", "reservationS11").ToString());
            if (this.Reservation.ApartmentReservation.Length > 1) {
                this.lblStatusLpApartmentsCount.Visible = false;
                this.lblStatusMpApartmentsCount.Visible = true;
            }
            this.rptReservationApartments.DataSource = this.statusReservationItems;
            this.rptReservationApartments.DataBind();

            if (this.ReservationOrderingServices.Any()) {
                this.rptStatusAdditionalServices.DataSource = this.ReservationOrderingServices;
                this.rptStatusAdditionalServices.DataBind();

                this.ltlComplexStatusApartmentValue.Value = this.Reservation.Price;
                this.ltlComplexStatusReservationValue.Value = this.Reservation.Price + this.ReservationOrderingServices.Sum(ras => ras.Price);
                this.phComplexStatusValue.Visible = true;
                this.lblStatusPrice.Visible = false;
                this.ltlStatusTotalRabatWarning.Visible = true;
            } else
                this.lblStatusPrice.Value = this.Reservation.Price;

            this.ltlStatusReservationNumber.Text = this.Reservation.ReservationNumber;
            this.ltlStatusName.Text = this.Reservation.Status.Name;
            this.ltlStatusDescription.Text = this.Reservation.Status.Description;

            this.ltlStatusPeriod.Text = this.Reservation.ArrivalDate.FormatDateRange(this.Reservation.DepartureDate);
            var lengthStay = (int)Math.Round((this.Reservation.DepartureDate - this.Reservation.ArrivalDate).TotalDays, 0);
            string lengthStayText = lengthStay + " ";
            string resxKey = "nights1";
            if (lengthStay > 1 && lengthStay <= 4)
                resxKey = "nights24";
            if (lengthStay > 4)
                resxKey = "nightsmore";
            lengthStayText += GetGlobalResourceObject("Reservation", resxKey);
            this.ltlStatusLengthOfStay.Text = lengthStayText;

// ReSharper disable once CompareOfFloatsByEqualityOperator
            if (this.Reservation.Rabat != 0) {
                this.pnlStatusRabat.Visible = true;
                this.ltlStatusTotalRabat.Text = String.Format("{0:F0}%", this.Reservation.Rabat);
                if (this.Reservation.ReservationRabats.Length > 0) {
                    this.rptStatusRabats.Visible = true;
                    this.rptStatusRabats.DataSource = this.Reservation.ReservationRabats;
                    this.rptStatusRabats.DataBind();
                }
                //this.ltlDiscounts.Text = String.Join("<br />", rNames);
                //this.ltlDiscountsValue.Text = String.Join("<br />", rValues);
            } else {
                this.pnlStatusRabat.Visible = false;
            }

            this.ltlStatusReservationFinalValue.Value = this.Reservation.FinalPrice;
            if (this.ReservationOrderingServices.Any())
                this.ltlStatusReservationFinalValue.Value += this.ReservationOrderingServices.Sum(ras => ras.Price);

            if (this.Reservation.PaymentType != null) {
                this.phStatusPaymentType.Visible = true;
                this.ltlStatusPaymentType.Text = this.Reservation.PaymentType.Name;
            }

            this.mvView.SetActiveView(this.vStatus);
        }

        private string GetPersonText(int persons) {
            string key;
            if (persons == 1)
                key = "personOne";
            else if ((persons > 1 && persons <= 4) || (persons > 20 && persons % 10 > 1 && persons % 10 <= 4))
                key = "personMoreOne";
            else
                key = "personMany";
            var reservationKeyText = GetGlobalResourceObject("Reservation", key);
            if (reservationKeyText != null)
                return reservationKeyText.ToString();
            return String.Empty;
        }

        private void PopulateErrorView() {
            this.mvView.SetActiveView(this.vUnavalible);
        }

        #endregion

        #region Methods

        private void SetAlternativeTitle(string title) {
            this.ltlReservationOnline.Visible = false;
            this.ltlAlternativeTitle.Text = title;
            this.ltlAlternativeTitle.Visible = true;
        }

        private void SetSubtitle(int stepNumber, string title) {
            bool showBreadcrumb = stepNumber > 0 && stepNumber <= 3;
            var sb = new StringBuilder("<h6>");
            if (showBreadcrumb)
                sb.AppendFormat("{0} {1}/3 ", GetGlobalResourceObject("Reservation", "step"), stepNumber);
            sb.Append(title);
            sb.Append("</h6>");
            this.ltlSubTitle.Text = sb.ToString();
            this.ltlSubTitle.Visible = true;
            if (showBreadcrumb)
                this.SetReservationCrumbActive(stepNumber);
        }

        private void SetReservationCrumbActive(int crumbPageNumber) {
            this.phReservationCrumbs.Visible = true;
            this.ActivePage = crumbPageNumber;
        }

        #endregion

        protected void lnkGotoContact_Click(object sender, EventArgs e) {
            this.SetScenarioForInformation(); // Refresh informacji z ekranu
            if (this.variant == null || this.variant.Items.Length == 0) {
                Response.Redirect(NavigationProvider.Instance().GetUrl(SearchState.Empty));
                return;
            }
            IWebReservation newReservation = this.factory.CreateWebReservation();
            foreach (VariantItem item in this.variant.Items) {
                if (item.ExtraBedService != null) {
                    newReservation.AddApartment(item.Apartment.Id, item.NumberOfPeoples - 1);
                } else
                    newReservation.AddApartment(item.Apartment.Id, item.NumberOfPeoples);
            }
            newReservation.SetDates(this.variant.Items[0].ArrivalDate, this.variant.Items[0].DepartureDate);
            newReservation.SetPrice(this.variant.ReservationPrice);

            newReservation.Save();
            if (this.variant.Items[0].ExtraBedService != null) {
                IAdditionalService extraBedService = this.variant.Items[0].ExtraBedService;
                ReservationAdditionalService extraBedServiceForNewReservation = extraBedService.AddToReservation(newReservation);
                DateTime st = newReservation.ArrivalDate.Date;
                DateTime et = newReservation.DepartureDate.AddDays(-1).Date;
                while (st <= et) {
                    extraBedServiceForNewReservation.BookService(st);
                    st = st.AddDays(1);
                }
                extraBedServiceForNewReservation.Save();
            }
            if (this.ReservationPage.OrderingBreakfasts) {
                var breakfastService = factory.GetAdditionalService()
                    .FindService(this.ReservationPage.ApartmentTypeId, "breakfasts");
                if (breakfastService != null) {
                    var cnt = this.variant.Items.Sum(vi => vi.NumberOfPeoples);
                    var reservationBreakfastService = breakfastService.AddToReservation(newReservation);
                    DateTime st = newReservation.ArrivalDate.Date.AddDays(1);
                    DateTime et = newReservation.DepartureDate.Date;
                    while (st <= et) {
                        reservationBreakfastService.BookService(st, cnt);
                        st = st.AddDays(1);
                    }
                    reservationBreakfastService.Save();
                }
            }
            Response.Redirect(NavigationProvider.Instance().GetUrl(ReservationPage.GetContactPage(newReservation)));
        }

        protected void lnkContactComplete_Click(object sender, EventArgs e) {
            if (Page.IsValid) {
                this.SetScenarioForContact();
                string email = Request[this.txtEMail.UniqueID];
                string firstName = Request[this.txtFirstName.UniqueID];
                string lastName = Request[this.txtLastName.UniqueID];
                string phone = Request[this.txtPhone.UniqueID];
                string comments = Request[this.txtOverview.UniqueID];
                string arrivalTime = Request[this.txtArrivalTime.UniqueID];

                IClient client = factory.GetClient(0).SearchClientByEmail(email);
                client.EMail = email;
                client.FirstName = firstName;
                client.LastName = lastName;
                client.PhoneNumber = phone;
                client.PrefferCurrency = DisplayCurrency.GetUserCurrency();
                client.PersonTitle = "p.";
                client.PrefferLanguage = CultureInfo.CurrentCulture.Name;
                if (!client.Save()) return;
                this.Reservation.SetClient(client);

                var timeParts = arrivalTime.Split(':');
                var hour = Int32.Parse(timeParts[0]);
                var minutes = Int32.Parse(timeParts[1]);
                if (hour < 14)
                    hour += 24;

                this.Reservation.SetArrivalTime(TimeSpan.FromMinutes(hour * 60 + minutes));
                this.Reservation.Comments = comments;
                if (this.Reservation.Save())
                    Response.Redirect(NavigationProvider.Instance().GetUrl(ReservationPage.GetPaymentPage(Reservation)));
            }
        }

        protected void rptPayments_ItemDataBound(object sender, RepeaterItemEventArgs e) {
            switch (e.Item.ItemType) {
                case ListItemType.AlternatingItem:
                case ListItemType.Item:
                    var paymentType = e.Item.DataItem as IPaymentType;
                    var rabatPriceValue = e.Item.FindControl("rabatPriceValue") as HiddenField;
                    var reservationValueWithRabat = e.Item.FindControl("reservationValueWithRabat") as HiddenField;
                    if (paymentType != null) {
                        var dc = new DisplayCurrency();
                        var currencyCode = dc.GetCurrentCurrency();
                        var rabatValue = this.Reservation.Price * paymentType.ExtraRabat / 100;
                        var reservationPriceWithRabat = this.ReservationPriceCalculator.TotalCost + rabatValue;
                        var curRabatPriceValue = new Currency(rabatValue, "PLN", 2);
                        var curReservationPriceWithRabat = new Currency(reservationPriceWithRabat, "PLN", 2);
                        if (rabatPriceValue != null)
                            rabatPriceValue.Value = curRabatPriceValue.ToCurrency(currencyCode).ToString();
                        if (reservationValueWithRabat != null)
                            reservationValueWithRabat.Value = curReservationPriceWithRabat.ToCurrency(currencyCode).ToString();
                    }
                    break;
            }
        }

        protected void lnkEndReservation_Click(object sender, EventArgs e) {
            string paymentKey = Request["payment_type"];
            if (string.IsNullOrEmpty(paymentKey) || !this.SetScenarioForPayments()) {
                this.PopulateErrorView();
                return;
            }
            IPaymentType paymentType = this.factory.GetPaymentType().GetWebPayments().FirstOrDefault(p => p.Key == paymentKey);
            if (paymentType == null) {
                this.PopulateErrorView();
                return;
            }
            this.Reservation.SetPaymentType(paymentType);
            this.Reservation.ChangeStatus("initial");
            Response.Redirect(NavigationProvider.Instance().GetUrl(ReservationPage.GetEndPage(Reservation)));
        }

        protected void rptReservationApartments_ItemDataBound(object sender, RepeaterItemEventArgs e) {
            switch (e.Item.ItemType) {
                case ListItemType.AlternatingItem:
                case ListItemType.Item:
                    var apartmentReservation = e.Item.DataItem as ApartmentWebReservation;
                    if (apartmentReservation != null) {
                        var reservationApartment = this.factory.GetApartment(apartmentReservation.ApartmentId);
                        var reservationApartmentGroup = reservationApartment.Group;


                        var imgStatusApartmentPhoto = e.Item.FindControl("imgStatusApartmentPhoto") as Image;
                        var ltlStatusApartmentsCount = e.Item.FindControl("ltlStatusApartmentsCount") as Literal;
                        var lblStatusApartmentName = e.Item.FindControl("lblStatusApartmentName") as Literal;
                        var lblStatusPeoples = e.Item.FindControl("lblStatusPeoples") as Literal;

                        if (imgStatusApartmentPhoto != null) {
                            imgStatusApartmentPhoto.ImageUrl = StareKinoHelper.GetApartmentPhotoUrl(reservationApartmentGroup.MainPhoto, new System.Drawing.Size(480, 480));
                            imgStatusApartmentPhoto.AlternateText = reservationApartmentGroup.ShortName;
                        }

                        if (lblStatusApartmentName != null)
                            lblStatusApartmentName.Text = reservationApartmentGroup.ShortName;
                        if (ltlStatusApartmentsCount != null)
                            ltlStatusApartmentsCount.Visible = false;
                        if (lblStatusPeoples != null) {
                            lblStatusPeoples.Text = apartmentReservation.PeopleCount + @" " + this.GetPersonText(apartmentReservation.PeopleCount);
                            if (this.ReservationExtraBedService != null && this.ReservationExtraBedService.GetQuantityPerDay(reservationApartment.Id) > 0) {
                                lblStatusPeoples.Text = lblStatusPeoples.Text + @" (" + GetGlobalResourceObject("Apartments", "extraBed") + @")";
                            }
                        }

                    } else
                        e.Item.Visible = false;
                    break;
            }
        }

        protected void ItemDataBound_rptComplexStatusAdditionalServices(object sender, RepeaterItemEventArgs e) {
            switch (e.Item.ItemType) {
                case ListItemType.Item:
                case ListItemType.AlternatingItem:
                    var ras = e.Item.DataItem as ReservationAdditionalService;
                    var ltlServiceName = e.Item.FindControl("ltlServiceName") as Literal;
                    var ltlAdditionalServiceValue = e.Item.FindControl("ltlAdditionalServiceValue") as CurrencyLiteral;
                    if (ras != null && ltlServiceName != null && ltlAdditionalServiceValue != null) {
                        ltlServiceName.Text = ras.Service.ServiceName;
                        ltlAdditionalServiceValue.Value = ras.Price;
                    } else
                        e.Item.Visible = false;
                    break;
            }
        }

    }
}